import { defineStore } from 'pinia'
import { useRouter } from 'vue-router'

export const useMainStore = defineStore('main', {
  state: () => ({
    hasRoutes: false,
    editableTabsValue: '/index',
    editableTabs: [
      {
        title: '首页',
        name: '/index',
      },
    ],
  }),
  getters: {
    GET_TOKEN: () => {
      console.log('storge中token值为：', sessionStorage.getItem('token'));
      return sessionStorage.getItem('token');
    },
    GET_MENULIST: () => {
      return JSON.parse(sessionStorage.getItem('menuList'));
    },
    GET_USERINFO: () => {
      console.log('storge中userInfo值为：', sessionStorage.getItem('userInfo'));
      return JSON.parse(sessionStorage.getItem('userInfo'));
    },
  },
  actions: {
    SET_TOKEN(token) {
      sessionStorage.setItem('token', token);
      console.log('setItem中token值为：', sessionStorage.getItem('token'));
    },
    SET_MENULIST(menuList) {
      sessionStorage.setItem('menuList', JSON.stringify(menuList));
    },
    SET_USERINFO(userInfo) {
      sessionStorage.setItem('userInfo', JSON.stringify(userInfo));
    },
    SET_ROUTES_STATE(hasRoutes) {
      this.hasRoutes = hasRoutes;
    },
    ADD_TABS(tab) {
      if (this.editableTabs.findIndex((e) => e.name === tab.path) === -1) {
        this.editableTabs.push({
          title: tab.name,
          name: tab.path,
        });
      }
      this.editableTabsValue = tab.path;
    },
    RESET_TABS() {
      this.editableTabsValue = '/index';
      this.editableTabs = [
        {
          title: '首页',
          name: '/index',
        },
      ];
    },
    logout() {
      this.RESET_TABS();
      window.sessionStorage.clear();
      const router = useRouter();
      router.replace('/login');
    },
  },
});
